<template>
  <div class="appointment-scheduling">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>医生排班管理</span>
        </div>
      </template>

      <div class="search-bar">
        <el-button-group class="week-control">
          <el-button :type="currentWeekBtn === 'prev' ? 'primary' : ''" @click="changeWeek(-1)">上一周</el-button>
          <el-button :type="currentWeekBtn === 'current' ? 'primary' : ''" @click="goToCurrentWeek">本周</el-button>
          <el-button :type="currentWeekBtn === 'next' ? 'primary' : ''" @click="changeWeek(1)">下一周</el-button>
        </el-button-group>
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="科室">
            <el-select v-model="queryParams.departmentId" placeholder="请选择科室" clearable style="width: 180px; margin: 0 10px;">
              <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryParams.patientName" placeholder="请输入病人姓名" clearable style="width: 180px; margin-right: 10px;" @change="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="schedule-calendar">
        <el-table :data="scheduleList" style="width: 100%" v-loading="loading" border ref="scheduleTable">
          <el-table-column prop="doctorName" label="医生姓名" fixed/>
          <el-table-column prop="departmentName" label="科室" fixed/>
          <el-table-column v-for="(day, idx) in weekDays" :key="day.date" :label="day.label">
            <el-table-column label="上午">
              <template #default="scope">
                <span>{{ getCellValue(scope.row, day.date, 'morning') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下午">
              <template #default="scope">
                <span>{{ getCellValue(scope.row, day.date, 'afternoon') }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-setting" @click="handleSetSchedule(scope.row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                         :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]"
                         :page-size="queryParams.pageSize"
                         layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 第一个弹框：医生排班详情 -->
    <el-dialog :title="selectedDoctor + '医生排班详情'" :visible.sync="detailVisible" width="900px" :close-on-click-modal="false">
      <div class="schedule-detail">
        <!-- 左侧橙色面板 -->
        <div class="left-panel">
          <div class="date-info">
            <div class="current-date">{{ formatDetailDate }}</div>
            <div class="weekday">{{ detailWeekday }}</div>
          </div>
          <div class="time-section">
            <div class="section-title">上午</div>
            <div class="time-info">接诊时间：{{ scheduleDetail.morningStartTime || '8:00' }} - {{ scheduleDetail.morningEndTime || '12:00' }}</div>
            <div class="source-info">号源数量：{{ scheduleDetail.morningCount || 0 }}</div>
            <div class="patient-info">已预约：{{ scheduleDetail.morningBooked || 0 }}</div>
            <template v-if="scheduleDetail.morningStatus === '接诊'">
              <div class="schedule-type">排班类型：{{ scheduleDetail.morningScheduleType || '门诊' }}</div>
              <div class="registration-fee">挂号费：¥{{ scheduleDetail.morningRegistrationFee || 0 }}</div>
              <div class="remark" v-if="scheduleDetail.morningRemark">备注：{{ scheduleDetail.morningRemark }}</div>
            </template>
          </div>
          <div class="time-section">
            <div class="section-title">下午</div>
            <div class="time-info">接诊时间：{{ scheduleDetail.afternoonStartTime || '14:00' }} - {{ scheduleDetail.afternoonEndTime || '18:00' }}</div>
            <div class="source-info">号源数量：{{ scheduleDetail.afternoonCount || 0 }}</div>
            <div class="patient-info">已预约：{{ scheduleDetail.afternoonBooked || 0 }}</div>
            <template v-if="scheduleDetail.afternoonStatus === '接诊'">
              <div class="schedule-type">排班类型：{{ scheduleDetail.afternoonScheduleType || '门诊' }}</div>
              <div class="registration-fee">挂号费：¥{{ scheduleDetail.afternoonRegistrationFee || 0 }}</div>
              <div class="remark" v-if="scheduleDetail.afternoonRemark">备注：{{ scheduleDetail.afternoonRemark }}</div>
            </template>
          </div>
        </div>
        <!-- 右侧日历 -->
        <div class="right-calendar">
          <div class="month-select">
            <el-date-picker v-model="currentMonth" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy-MM" />
          </div>
          <div class="calendar-grid">
            <div class="week-header">
              <div v-for="day in ['周日', '周一', '周二', '周三', '周四', '周五', '周六']" :key="day" class="week-day">{{ day }}</div>
            </div>
            <div class="days-grid">
              <div v-for="date in calendarDates" :key="date.fullDate" :class="['date-cell', { 'current-month': !date.isOtherMonth, 'selected': selectedDetailDate === date.fullDate }]" @click="handleDetailDateSelect(date)">
                <div class="date-number">
                  {{ date.day }}
                  <span class="weekday">{{ date.weekday }}</span>
                </div>
                <div v-if="!date.isOtherMonth" class="schedule-text">
                  <template v-if="getScheduleStatus(date)">
                    <div>上：{{ getScheduleMorningText(date) }}</div>
                    <div>下：{{ getScheduleAfternoonText(date) }}</div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="openScheduleDialog">设置排班</el-button>
        <el-button type="danger" size="small" @click="closeDoctorSchedule">关闭预约</el-button>
        <el-button size="small" @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 第二个弹框：排班设置 -->
    <el-dialog :title="selectedDoctor + '医生排班设置'" :visible.sync="scheduleVisible" width="1000px">
      <div class="schedule-detail">
        <!-- 左侧橙色面板 -->
        <div class="left-panel">
          <div class="date-info">
            <div class="current-date">{{ formatSelectedDate }}</div>
            <div class="weekday">{{ selectedWeekday }}</div>
          </div>
          <div class="time-section">
            <div class="section-title">上午</div>
            <div class="schedule-status">
              <el-radio-group v-model="scheduleForm.morningStatus" size="small">
                <el-radio label="接诊">接诊</el-radio>
                <el-radio label="休息">休息</el-radio>
              </el-radio-group>
            </div>
            <template v-if="scheduleForm.morningStatus === '接诊'">
              <div class="time-info">
                接诊时间：
                <el-time-select v-model="scheduleForm.morningStartTime" placeholder="开始时间" :picker-options="{ start: '08:00', step: '00:30', end: '12:00' }" size="small" />
                -
                <el-time-select v-model="scheduleForm.morningEndTime" placeholder="结束时间" :picker-options="{ start: '08:00', step: '00:30', end: '12:00', minTime: scheduleForm.morningStartTime }" size="small" />
              </div>
              <div class="source-input">
                号源数量：
                <el-input-number v-model="scheduleForm.morningCount" :min="0" :max="100" size="small" />
              </div>
            </template>
          </div>
          <div class="time-section">
            <div class="section-title">下午</div>
            <div class="schedule-status">
              <el-radio-group v-model="scheduleForm.afternoonStatus" size="small">
                <el-radio label="接诊">接诊</el-radio>
                <el-radio label="休息">休息</el-radio>
              </el-radio-group>
            </div>
            <template v-if="scheduleForm.afternoonStatus === '接诊'">
              <div class="time-info">
                接诊时间：
                <el-time-select v-model="scheduleForm.afternoonStartTime" placeholder="开始时间" :picker-options="{ start: '14:00', step: '00:30', end: '18:00' }" size="small" />
                -
                <el-time-select v-model="scheduleForm.afternoonEndTime" placeholder="结束时间" :picker-options="{ start: '14:00', step: '00:30', end: '18:00', minTime: scheduleForm.afternoonStartTime }" size="small" />
              </div>
              <div class="source-input">
                号源数量：
                <el-input-number v-model="scheduleForm.afternoonCount" :min="0" :max="100" size="small" />
              </div>
            </template>
          </div>
        </div>
        <!-- 右侧日历 -->
        <div class="right-calendar">
          <div class="month-select">
            <el-date-picker v-model="currentMonth" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy-MM" />
          </div>
          <div class="calendar-grid">
            <div class="week-header">
              <div v-for="day in ['周日', '周一', '周二', '周三', '周四', '周五', '周六']" :key="day" class="week-day">{{ day }}</div>
            </div>
            <div class="days-grid">
              <div v-for="date in calendarDates" :key="date.date" :class="['date-cell', { 'current-month': !date.isOtherMonth, 'selected': selectedDates.includes(date.fullDate) }]" @click="toggleDateSelection(date)">
                <div class="date-number">
                  {{ date.day }}
                  <span class="weekday">{{ date.weekday }}</span>
                </div>
                <div v-if="!date.isOtherMonth" class="schedule-text">{{ getScheduleText(date) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSchedule">保存设置</el-button>
        <el-button @click="scheduleVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchScheduleList,
  getDoctorScheduleDetail,
  setDoctorSchedule,
  closeSchedule,
  getParentDepartmentList,
} from '@/api/system/schedule'

export default {
  name: 'AppointmentScheduling',
  data() {
    return {
      currentWeekBtn: 'current',
      weekStart: '', // 本周起始日期
      weekEnd: '',   // 本周结束日期
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        departmentId: undefined,
        patientName: undefined
      },
      total: 0,
      scheduleList: [],
      departments: [],
      currentDoctor: null,
      selectedDoctor: '',
      selectedDoctorId: null,
      detailVisible: false,
      scheduleVisible: false,
      selectedDetailDate: null,
      selectedDates: [],
      currentMonth: '',
      calendarDates: [],
      scheduleForm: {
        morningStatus: '接诊',
        morningStartTime: '08:00',
        morningEndTime: '12:00',
        morningCount: 20,
        afternoonStatus: '接诊',
        afternoonStartTime: '14:00',
        afternoonEndTime: '18:00',
        afternoonCount: 20
      },
      scheduleDetail: {
        morningStatus: '未排班',
        morningCount: 0,
        morningBooked: 0,
        afternoonStatus: '未排班',
        afternoonCount: 0,
        afternoonBooked: 0
      },
      weekDays: []
    }
  },
  computed: {
    formatSelectedDate() {
      if (!this.selectedDates || this.selectedDates.length === 0) return ''
      const date = new Date(this.selectedDates[0])
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },
    selectedWeekday() {
      if (!this.selectedDates || this.selectedDates.length === 0) return ''
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      const date = new Date(this.selectedDates[0])
      return weekdays[date.getDay()]
    },
    formatDetailDate() {
      if (!this.selectedDetailDate) {
        const now = new Date()
        return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
      }
      const date = new Date(this.selectedDetailDate)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },
    detailWeekday() {
      if (!this.selectedDetailDate) {
        const now = new Date()
        return ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()]
      }
      const date = new Date(this.selectedDetailDate)
      return ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()]
    }
  },
  created() {
    this.initWeek();
    this.getList();
    this.fetchDepartments();
    const now = new Date();
    this.currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
  },
  mounted() {
    // 监听窗口大小变化，调整表格布局
    window.addEventListener('resize', this.$_handleResize);
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.$_handleResize);
  },
  methods: {
    $_handleResize() {
      if (this.$refs.scheduleTable) {
        this.$refs.scheduleTable.doLayout();
      }
    },
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    getScheduleValue(schedule, period) {
      if (!schedule) return '未排班'
      const status = schedule[`${period}Status`]
      const count = schedule[`${period}Count`] || 0
      const booked = schedule[`${period}Booked`] || 0
      return status === '接诊' ? `${booked}/${count}` : '休息'
    },
    initWeek() {
      const today = new Date();
      const day = today.getDay() || 7; // 周日为0，转为7
      const monday = new Date(today);
      monday.setDate(today.getDate() - day + 1);
      const sunday = new Date(monday);
      sunday.setDate(monday.getDate() + 6);

      this.weekStart = this.formatDate(monday);
      this.weekEnd = this.formatDate(sunday);
      this.weekDays = [];

      for (let i = 0; i < 7; i++) {
        const d = new Date(monday);
        d.setDate(monday.getDate() + i);
        const month = d.getMonth() + 1;
        const date = d.getDate();
        const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][d.getDay()];
        this.weekDays.push({
          date: this.formatDate(d),
          label: `${month}/${date} ${weekDay}`
        });
      }
    },
    changeWeek(offset) {
      this.currentWeekBtn = offset === -1 ? 'prev' : 'next';
      const start = new Date(this.weekStart);
      start.setDate(start.getDate() + offset * 7);

      this.weekStart = this.formatDate(start);
      this.weekDays = [];

      for (let i = 0; i < 7; i++) {
        const d = new Date(start);
        d.setDate(start.getDate() + i);
        const month = d.getMonth() + 1;
        const date = d.getDate();
        const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][d.getDay()];
        this.weekDays.push({
          date: this.formatDate(d),
          label: `${month}/${date} ${weekDay}`
        });
      }

      const end = new Date(start);
      end.setDate(start.getDate() + 6);
      this.weekEnd = this.formatDate(end);

      this.getList();
    },
    goToCurrentWeek() {
      this.currentWeekBtn = 'current';
      this.initWeek();
      this.getList();
    },
    getList() {
      this.loading = true;
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        departmentId: this.queryParams.departmentId || undefined,
        patientName: this.queryParams.patientName || undefined,
        weekStart: this.weekStart,
        weekEnd: this.weekEnd
      };
      console.log('查询参数：', params);
      fetchScheduleList(params).then(res => {
        console.log('返回数据：', res);
        if (res.rows && Array.isArray(res.rows)) {
          // 按医生分组数据
          const doctorMap = new Map();

          // 处理返回的数据
          res.rows.forEach(item => {
            const doctorId = item.doctorId;
            if (!doctorMap.has(doctorId)) {
              doctorMap.set(doctorId, {
                doctorId: item.doctorId,
                doctorName: item.doctorName,
                departmentId: item.departmentId,
                departmentName: item.departmentName,
                schedules: {}
              });
            }

            const doctor = doctorMap.get(doctorId);
            const scheduleDate = item.scheduleDate;

            // 初始化该日期的排班数据
            if (!doctor.schedules[scheduleDate]) {
              doctor.schedules[scheduleDate] = {
                morning: { status: '未排班', count: 0, booked: 0 },
                afternoon: { status: '未排班', count: 0, booked: 0 }
              };
            }

            // 根据period设置排班数据
            const timeSlot = item.period === 1 ? 'morning' :
                           item.period === 2 ? 'afternoon' : null;

            if (timeSlot) {
              doctor.schedules[scheduleDate][timeSlot] = {
                status: '接诊',
                count: item.totalNum || 0,
                booked: (item.totalNum - item.availableNum) || 0,
                startTime: item.startTime,
                endTime: item.endTime,
                scheduleType: item.scheduleType,
                registrationFee: item.registrationFee,
                remark: item.remark
              };
            }
          });

          // 转换为数组并确保每个医生都有完整的一周排班数据
          const formattedData = Array.from(doctorMap.values()).map(doctor => {
            // 确保每天都有数据
            this.weekDays.forEach(day => {
              if (!doctor.schedules[day.date]) {
                doctor.schedules[day.date] = {
                  morning: { status: '未排班', count: 0, booked: 0 },
                  afternoon: { status: '未排班', count: 0, booked: 0 }
                };
              }
            });
            return doctor;
          });

          this.scheduleList = formattedData;
          this.total = res.total || 0;

          console.log('处理后的数据：', this.scheduleList);
        } else {
          this.scheduleList = [];
          this.total = 0;
          this.$message.error('获取排班列表失败：返回数据格式不正确');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取排班列表错误：', error);
        this.scheduleList = [];
        this.total = 0;
        this.loading = false;
        this.$message.error('获取排班列表失败');
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    handleSetSchedule(row) {
      this.currentDoctor = row;
      this.selectedDoctor = row.doctorName;
      this.selectedDoctorId = row.doctorId;
      this.detailVisible = true;
      const today = this.formatDate(new Date());
      this.selectedDetailDate = today;
      this.currentMonth = today.substring(0, 7);
      this.getScheduleDetail(row.doctorId, today);
    },
    getScheduleDetail(doctorId, date) {
      // 获取上午排班
      getDoctorScheduleDetail(doctorId, date, '上午').then(response => {
        if (response.code === 200 && response.data) {
          const schedule = response.data;
          this.scheduleDetail = {
            ...this.scheduleDetail,
            morningStatus: schedule.period === 1 ? '接诊' : '休息',
            morningCount: schedule.totalNum || 0,
            morningBooked: schedule.totalNum - schedule.availableNum || 0,
            morningStartTime: schedule.startTime,
            morningEndTime: schedule.endTime,
            morningRegistrationFee: schedule.registrationFee,
            morningScheduleType: schedule.scheduleType,
            morningRemark: schedule.remark
          };
        } else {
          this.scheduleDetail = {
            ...this.scheduleDetail,
            morningStatus: '未排班',
            morningCount: 0,
            morningBooked: 0,
            morningStartTime: '',
            morningEndTime: '',
            morningRegistrationFee: 0,
            morningScheduleType: '',
            morningRemark: ''
          };
        }
      }).catch(() => {
        this.scheduleDetail = {
          ...this.scheduleDetail,
          morningStatus: '未排班',
          morningCount: 0,
          morningBooked: 0,
          morningStartTime: '',
          morningEndTime: '',
          morningRegistrationFee: 0,
          morningScheduleType: '',
          morningRemark: ''
        };
      });

      // 获取下午排班
      getDoctorScheduleDetail(doctorId, date, '下午').then(response => {
        if (response.code === 200 && response.data) {
          const schedule = response.data;
          this.scheduleDetail = {
            ...this.scheduleDetail,
            afternoonStatus: schedule.period === 2 ? '接诊' : '休息',
            afternoonCount: schedule.totalNum || 0,
            afternoonBooked: schedule.totalNum - schedule.availableNum || 0,
            afternoonStartTime: schedule.startTime,
            afternoonEndTime: schedule.endTime,
            afternoonRegistrationFee: schedule.registrationFee,
            afternoonScheduleType: schedule.scheduleType,
            afternoonRemark: schedule.remark
          };
        } else {
          this.scheduleDetail = {
            ...this.scheduleDetail,
            afternoonStatus: '未排班',
            afternoonCount: 0,
            afternoonBooked: 0,
            afternoonStartTime: '',
            afternoonEndTime: '',
            afternoonRegistrationFee: 0,
            afternoonScheduleType: '',
            afternoonRemark: ''
          };
        }
      }).catch(() => {
        this.scheduleDetail = {
          ...this.scheduleDetail,
          afternoonStatus: '未排班',
          afternoonCount: 0,
          afternoonBooked: 0,
          afternoonStartTime: '',
          afternoonEndTime: '',
          afternoonRegistrationFee: 0,
          afternoonScheduleType: '',
          afternoonRemark: ''
        };
      });
    },
    openScheduleDialog() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const selectedDate = new Date(this.selectedDetailDate);
      selectedDate.setHours(0, 0, 0, 0);
      if (selectedDate < today) {
        this.$message({ message: '不能对过去的日期进行排班设置', type: 'warning' });
        return;
      }
      this.scheduleVisible = true;
      this.scheduleForm = {
        morningStatus: '接诊',
        morningStartTime: '08:00',
        morningEndTime: '12:00',
        morningCount: 20,
        afternoonStatus: '接诊',
        afternoonStartTime: '14:00',
        afternoonEndTime: '18:00',
        afternoonCount: 20
      };
      this.selectedDates = [this.selectedDetailDate];
    },
    saveSchedule() {
      if (!this.selectedDates || this.selectedDates.length === 0) {
        this.$message.warning('请选择排班日期');
        return;
      }

      const schedules = [];
      // 处理每个选中的日期
      this.selectedDates.forEach(date => {
        // 如果上午选择接诊，添加上午排班
        if (this.scheduleForm.morningStatus === '接诊') {
          schedules.push({
            doctorId: this.selectedDoctorId,
            departmentId: this.currentDoctor.departmentId,
            scheduleDate: date,
            period: 1, // 上午
            totalNum: this.scheduleForm.morningCount,
            availableNum: this.scheduleForm.morningCount, // 初始可用号源等于总号源
            startTime: this.formatDateTime(date, this.scheduleForm.morningStartTime),
            endTime: this.formatDateTime(date, this.scheduleForm.morningEndTime),
            scheduleType: '门诊',
            registrationFee: 25, // 默认挂号费
            remark: '',
            patientId: 0, // 设置默认值为0，表示还未有病人预约
            createUser: 'admin', // 设置创建人
            updateUser: 'admin'  // 设置更新人
          });
        }

        // 如果下午选择接诊，添加下午排班
        if (this.scheduleForm.afternoonStatus === '接诊') {
          schedules.push({
            doctorId: this.selectedDoctorId,
            departmentId: this.currentDoctor.departmentId,
            scheduleDate: date,
            period: 2, // 下午
            totalNum: this.scheduleForm.afternoonCount,
            availableNum: this.scheduleForm.afternoonCount, // 初始可用号源等于总号源
            startTime: this.formatDateTime(date, this.scheduleForm.afternoonStartTime),
            endTime: this.formatDateTime(date, this.scheduleForm.afternoonEndTime),
            scheduleType: '门诊',
            registrationFee: 25, // 默认挂号费
            remark: '',
            patientId: 0, // 设置默认值为0，表示还未有病人预约
            createUser: 'admin', // 设置创建人
            updateUser: 'admin'  // 设置更新人
          });
        }
      });

      // 批量保存排班信息
      const promises = schedules.map(schedule => setDoctorSchedule(schedule));

      Promise.all(promises)
        .then(responses => {
          // 检查是否所有请求都成功
          const allSuccess = responses.every(res => res.code === 200);
          if (allSuccess) {
            this.$message.success('排班设置成功');
            this.scheduleVisible = false;
            this.detailVisible = false;
            this.selectedDates = [];
            this.getList();
          } else {
            this.$message.error('部分排班设置失败，请重试');
          }
        })
        .catch(() => {
          this.$message.error('排班设置失败，请稍后重试');
        });
    },
    formatDateTime(date, time) {
      // 将时间格式化为 "yyyy-MM-dd HH:ss:mm"
      const [hours, minutes] = time.split(':');
      return `${date} ${hours}:${minutes}:00`;
    },
    closeDoctorSchedule() {
      if (!this.selectedDoctorId) {
        this.$message.warning('请先选择医生');
        return;
      }
      this.$confirm('关闭后该医生所有排班将被取消，用户将无法预约，是否确认关闭?', '关闭预约确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        closeSchedule(this.selectedDoctorId).then(response => {
          if (response.code === 200) {
            this.$message.success('关闭预约成功');
            this.getList();
            this.detailVisible = false;
          } else {
            this.$message.error(response.msg || '关闭预约失败');
          }
        }).catch(() => {
          this.$message.error('关闭预约失败，请稍后重试');
        });
      });
    },
    initCalendarDates(yearMonth) {
      const [year, month] = yearMonth.split('-').map(Number)
      const firstDay = new Date(year, month - 1, 1)
      const lastDay = new Date(year, month, 0)
      const dates = []
      const firstDayWeek = firstDay.getDay()
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

      for (let i = firstDayWeek - 1; i >= 0; i--) {
        const date = new Date(year, month - 1, -i)
        dates.push({
          day: date.getDate(),
          fullDate: this.formatDate(date),
          isOtherMonth: true,
          weekday: weekdays[date.getDay()]
        })
      }
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month - 1, i)
        dates.push({
          day: i,
          fullDate: this.formatDate(date),
          isOtherMonth: false,
          weekday: weekdays[date.getDay()]
        })
      }
      const remainingDays = 42 - dates.length
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month, i)
        dates.push({
          day: i,
          fullDate: this.formatDate(date),
          isOtherMonth: true,
          weekday: weekdays[date.getDay()]
        })
      }
      this.calendarDates = dates
    },
    getScheduleText(date) {
      if (this.currentDoctor && this.currentDoctor.schedules) {
        const schedule = this.currentDoctor.schedules[date.fullDate]
        if (schedule) {
          const morning = schedule.morningStatus === '接诊' ? `号源 ${schedule.morningCount}` : ''
          const afternoon = schedule.afternoonStatus === '接诊' ? `号源 ${schedule.afternoonCount}` : ''
          if (morning || afternoon) {
            return `${morning}\n${afternoon}`.trim()
          }
        }
      }
      return ''
    },
    formatYearMonth(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      return `${year}-${month}`
    },
    isSelectedDate(date) {
      return date.fullDate === this.formatDate(new Date(
        new Date().getFullYear(),
        new Date().getMonth() + 1,
        new Date().getDate()
      ))
    },
    toggleDateSelection(date) {
      if (date.isOtherMonth) return
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const selectedDate = new Date(date.fullDate)
      selectedDate.setHours(0, 0, 0, 0)
      if (selectedDate < today) {
        this.$message({ message: '不能对过去的日期进行排班设置', type: 'warning' })
        return
      }
      const index = this.selectedDates.indexOf(date.fullDate)
      if (index === -1) {
        this.selectedDates.push(date.fullDate)
      } else {
        this.selectedDates.splice(index, 1)
      }
    },
    handleDetailDateSelect(date) {
      if (date.isOtherMonth) return
      this.selectedDetailDate = date.fullDate
      if (this.currentDoctor && this.currentDoctor.schedules) {
        const schedule = this.currentDoctor.schedules[date.fullDate]
        if (schedule) {
          this.scheduleDetail = {
            morningStatus: schedule.morningStatus,
            morningCount: schedule.morningCount,
            morningBooked: schedule.morningBooked,
            afternoonStatus: schedule.afternoonStatus,
            afternoonCount: schedule.afternoonCount,
            afternoonBooked: schedule.afternoonBooked
          }
        } else {
          this.scheduleDetail = {
            morningStatus: '未排班',
            morningCount: 0,
            morningBooked: 0,
            afternoonStatus: '未排班',
            afternoonCount: 0,
            afternoonBooked: 0
          }
        }
      }
    },
    fetchDepartments() {
      getParentDepartmentList().then(response => {
        console.log('科室列表数据：', response); // 添加日志
        if (response.code === 200) {
          this.departments = response.data || [];
        } else {
          this.$message.error(response.msg || '获取科室列表失败');
        }
      }).catch(error => {
        console.error('获取科室列表错误：', error); // 添加错误日志
        this.$message.error('获取科室列表失败');
      });
    },
    handleDepartmentChange(value) {
      if (value) {
        this.queryParams.departmentId = value[value.length - 1]
      } else {
        this.queryParams.departmentId = null
      }
      this.handleQuery()
    },
    isScheduled(date) {
      if (date.isOtherMonth || !this.currentDoctor || !this.currentDoctor.schedules) {
        return false
      }
      const schedule = this.currentDoctor.schedules[date.fullDate]
      return schedule && (schedule.morningStatus === '接诊' || schedule.afternoonStatus === '接诊')
    },
    handleDetail(row, date, period) {
      this.currentDoctor = row;
      this.selectedDoctor = row.doctorName;
      this.selectedDoctorId = row.doctorId;
      this.detailVisible = true;
      this.selectedDetailDate = date;
      this.currentMonth = date.substring(0, 7);

      // 获取上午排班
      getDoctorScheduleDetail(row.doctorId, date, '上午').then(response => {
        if (response.code === 200 && response.data) {
          const schedule = response.data;
          this.scheduleDetail = {
            ...this.scheduleDetail,
            morningStatus: schedule.period === 1 ? '接诊' : '休息',
            morningCount: schedule.totalNum || 0,
            morningBooked: schedule.totalNum - schedule.availableNum || 0,
            morningStartTime: schedule.startTime?.substring(11, 16) || '08:00',
            morningEndTime: schedule.endTime?.substring(11, 16) || '12:00',
            morningRegistrationFee: schedule.registrationFee || 0,
            morningScheduleType: schedule.scheduleType || '门诊',
            morningRemark: schedule.remark || ''
          };
        } else {
          this.scheduleDetail = {
            ...this.scheduleDetail,
            morningStatus: '未排班',
            morningCount: 0,
            morningBooked: 0,
            morningStartTime: '08:00',
            morningEndTime: '12:00',
            morningRegistrationFee: 0,
            morningScheduleType: '',
            morningRemark: ''
          };
        }
      }).catch(() => {
        this.scheduleDetail = {
          ...this.scheduleDetail,
          morningStatus: '未排班',
          morningCount: 0,
          morningBooked: 0,
          morningStartTime: '08:00',
          morningEndTime: '12:00',
          morningRegistrationFee: 0,
          morningScheduleType: '',
          morningRemark: ''
        };
      });

      // 获取下午排班
      getDoctorScheduleDetail(row.doctorId, date, '下午').then(response => {
        if (response.code === 200 && response.data) {
          const schedule = response.data;
          this.scheduleDetail = {
            ...this.scheduleDetail,
            afternoonStatus: schedule.period === 2 ? '接诊' : '休息',
            afternoonCount: schedule.totalNum || 0,
            afternoonBooked: schedule.totalNum - schedule.availableNum || 0,
            afternoonStartTime: schedule.startTime?.substring(11, 16) || '14:00',
            afternoonEndTime: schedule.endTime?.substring(11, 16) || '18:00',
            afternoonRegistrationFee: schedule.registrationFee || 0,
            afternoonScheduleType: schedule.scheduleType || '门诊',
            afternoonRemark: schedule.remark || ''
          };
        } else {
          this.scheduleDetail = {
            ...this.scheduleDetail,
            afternoonStatus: '未排班',
            afternoonCount: 0,
            afternoonBooked: 0,
            afternoonStartTime: '14:00',
            afternoonEndTime: '18:00',
            afternoonRegistrationFee: 0,
            afternoonScheduleType: '',
            afternoonRemark: ''
          };
        }
      }).catch(() => {
        this.scheduleDetail = {
          ...this.scheduleDetail,
          afternoonStatus: '未排班',
          afternoonCount: 0,
          afternoonBooked: 0,
          afternoonStartTime: '14:00',
          afternoonEndTime: '18:00',
          afternoonRegistrationFee: 0,
          afternoonScheduleType: '',
          afternoonRemark: ''
        };
      });
    },
    getScheduleStatus(date) {
      if (date.isOtherMonth || !this.currentDoctor || !this.currentDoctor.schedules) {
        return false
      }
      const schedule = this.currentDoctor.schedules[date.fullDate]
      return schedule && (schedule.morningStatus === '接诊' || schedule.afternoonStatus === '接诊')
    },
    getScheduleMorningText(date) {
      if (this.currentDoctor && this.currentDoctor.schedules) {
        const schedule = this.currentDoctor.schedules[date.fullDate]
        if (schedule) {
          return schedule.morningStatus === '接诊' ? `号源 ${schedule.morningCount}` : '休息'
        }
      }
      return '未排班'
    },
    getScheduleAfternoonText(date) {
      if (this.currentDoctor && this.currentDoctor.schedules) {
        const schedule = this.currentDoctor.schedules[date.fullDate]
        if (schedule) {
          return schedule.afternoonStatus === '接诊' ? `号源 ${schedule.afternoonCount}` : '休息'
        }
      }
      return '未排班'
    },
    getCellClass(schedule, period) {
      if (!schedule) return 'cell-empty';
      const status = schedule[period + 'Status'];
      if (status === '接诊') return 'cell-on-duty';
      if (status === '休息') return 'cell-rest';
      return 'cell-empty';
    },
    handleViewSchedule(doctorId, date) {
      this.loading = true
      getDoctorScheduleDetail(doctorId, date).then(response => {
        this.scheduleDetail = response.data
        this.dialogVisible = true
      }).catch(() => {
        this.$message.error('获取排班详情失败')
      }).finally(() => {
        this.loading = false
      })
    },
    handleCloseSchedule(doctorId) {
      this.$confirm('确认关闭该医生的排班吗？', '提示', {
        type: 'warning'
      }).then(() => {
        closeSchedule(doctorId).then(() => {
          this.$message.success('关闭成功')
          this.getList()
        }).catch(() => {
          this.$message.error('关闭失败')
        })
      })
    },
    submitSchedule() {
      this.$refs.scheduleForm.validate(valid => {
        if (valid) {
          setDoctorSchedule(this.scheduleForm).then(() => {
            this.$message.success('设置成功')
            this.dialogVisible = false
            this.getList()
          }).catch(() => {
            this.$message.error('设置失败')
          })
        }
      })
    },
    getCellValue(row, date, period) {
      if (!row.schedules || !row.schedules[date] || !row.schedules[date][period]) {
        return '未排班';
      }
      const schedule = row.schedules[date][period];
      return schedule.status === '接诊' ? `${schedule.booked}/${schedule.count}` : schedule.status;
    }
  },
  watch: {
    currentMonth: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initCalendarDates(val);
        }
      }
    },
    detailVisible(val) {
      if (val) {
        // 当弹窗打开时，初始化日历数据
        const today = this.formatDate(new Date());
        this.selectedDetailDate = today;
        this.currentMonth = today.substring(0, 7);
        this.initCalendarDates(this.currentMonth);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.appointment-scheduling {
  padding: 20px;
}

.el-dialog {
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
  border-radius: 12px;

  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.week-control {
  margin-right: 20px;

  .el-button {
    &.el-button--primary {
      background-color: #409EFF;
      border-color: #409EFF;
      color: #fff;
    }
  }
}

.schedule-calendar {
  margin-top: 20px;
}

.schedule-cell-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 60px;
}

.cell-on-duty {
  color: #F56C6C;
  font-weight: bold;
  cursor: pointer;
}

.cell-rest {
  color: #c0c4cc;
  cursor: pointer;
}

.cell-empty {
  color: #c0c4cc;
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.schedule-detail {
  display: flex;
  gap: 40px;
  min-height: 420px;
  padding: 20px;
}

.left-panel {
  width: 260px;
  background: linear-gradient(135deg, #ff9b44 0%, #fc6075 100%);
  border-radius: 8px;
  padding: 24px 18px;
  color: white;

  .date-info {
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    margin-bottom: 18px;
    padding-bottom: 10px;

    .current-date {
      font-size: 22px;
      font-weight: bold;
      margin-bottom: 6px;
    }

    .weekday {
      font-size: 16px;
      opacity: 0.85;
    }
  }

  .time-section {
    margin-bottom: 20px;

    .section-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 12px;
    }

    .time-info, .source-info, .patient-info, .schedule-type, .registration-fee, .remark {
      font-size: 14px;
      margin-bottom: 8px;
      opacity: 0.9;
    }

    .registration-fee {
      color: #F56C6C;
      font-weight: bold;
    }

    .remark {
      color: #909399;
      font-style: italic;
    }

    .schedule-type {
      color: #409EFF;
    }
  }
}

.right-calendar {
  flex: 1;

  .month-select {
    margin-bottom: 20px;
    text-align: center;
  }

  .calendar-grid {
    .week-header {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      margin-bottom: 10px;

      .week-day {
        padding: 8px 0;
        font-weight: bold;
        color: #606266;
      }
    }

    .days-grid {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 8px;
    }

    .date-cell {
      height: 65px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      padding: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &.current-month {
        background: #fff;

        &:hover {
          background: #f5f7fa;
          border-color: #409EFF;
        }

        &.selected {
          background: #e6f7ff;
          border-color: #1890ff;
        }
      }

      &:not(.current-month) {
        background: #f5f7fa;
        color: #c0c4cc;
        cursor: not-allowed;
      }

      .date-number {
        font-size: 14px;
        font-weight: bold;
        text-align: center;
        margin-bottom: 4px;
        display: flex;
        flex-direction: column;
        align-items: center;

        .weekday {
          font-size: 12px;
          color: #606266;
          font-weight: normal;
          margin-top: 2px;
        }
      }

      .schedule-text {
        min-height: 20px;  // 添加最小高度以保持单元格大小一致
        font-size: 12px;
        color: #409EFF;  // 使用主题蓝色显示号源信息
        text-align: center;
        line-height: 1.2;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;

  .el-button {
    margin-left: 10px;

    &.el-button--primary {
      background-color: #409EFF;
      border-color: #409EFF;
    }

    &.el-button--danger {
      background-color: #F56C6C;
      border-color: #F56C6C;
    }
  }
}
</style>
